package com.yk.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yk.api.system.dto.UserWxDTO;
import com.yk.common.core.domain.Result;
import com.yk.system.convert.UserWxConvert;
import com.yk.system.entity.User;
import com.yk.system.entity.UserWx;
import com.yk.system.service.UserService;
import com.yk.system.service.UserWxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;


/**
 * 用户-微信关联表 前端控制器
 *
 * @author lmx
 * @since 2023-11-29
 */
@Api(tags = "用户-微信关联表")
@RestController
@RequestMapping("/userWx")
@RequiredArgsConstructor
public class UserWxController {

    private final UserService userService;
    private final UserWxService userWxService;
    private final UserWxConvert userWxConvert;

    @ApiOperation("通过手机号查询用户微信关联信息")
    @GetMapping("/wxInfoByPhone")
    public Result<Boolean> getWxInfoByPhone(String phone) {
        LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<>();
        lambda.select(User::getId, User::getUserName, User::getStatus, User::getPassword, User::getPhone, User::getNickName);
        lambda.eq(User::getPhone, phone);
        User user = userService.getOne(lambda);
        if (Objects.isNull(user)) {
            return Result.data(Boolean.FALSE);
        }
        UserWx userWx = userWxService.getOne(new LambdaQueryWrapper<UserWx>().eq(UserWx::getUserId, user.getId()));
        if (Objects.isNull(userWx) || Objects.isNull(userWx.getGOpenId())) {
            return Result.data(Boolean.FALSE);
        }
        return Result.data(Boolean.TRUE);
    }

    @PostMapping("/saveUserWx")
    @ApiOperation("用户-微信关联表-新增")
    public Result<Boolean> save(@RequestBody @Validated UserWxDTO dto) {
        UserWx userWx = userWxConvert.dto2Entity(dto);
        LambdaQueryWrapper<UserWx> lambda = new LambdaQueryWrapper<>();
        lambda.eq(UserWx::getUserId, userWx.getUserId());
        UserWx result = userWxService.getOne(lambda);
        if (Objects.nonNull(result)) {
            result.setXOpenId(userWx.getXOpenId());
            result.setGOpenId(userWx.getGOpenId());
            result.setUnionId(userWx.getUnionId());
            userWxService.updateById(result);
            return Result.ok();
        }
        return Result.data(userWxService.save(userWx));
    }
}